{ src
, nodejs
, electron
}:
{ lib
, eudev
, npmlock2nix
, python3
, stdenv
, writeText
, ...
}:

let
  inherit (lib) optionals;
  inherit (stdenv) isLinux;
in

npmlock2nix.node_modules {
  inherit src nodejs;

  ELECTRON_SKIP_BINARY_DOWNLOAD = 1;
  npm_config_build_from_source = "true";
  npm_config_fund = false;
  npm_config_runtime = "electron";
  npm_config_tarball = electron.headers;
  npm_config_target = electron.version;

  nativeBuildInputs = [
    python3.out
  ] ++ optionals isLinux [
    eudev.out   # libudev.h
  ];

  preInstallLinks = {
    "electron" = {
      "dist" = "${electron}/lib/electron";
      "path.txt" = writeText "path.txt" "electron";
    };
  };

  installCommands = [
    "npm ci --ignore-scripts --offline"
    ''
      SCRIPT="$(readlink -f ./node_modules/.hooks/preinstall)"
      package_dirs="$(find ./node_modules -type f -name "package.json" | xargs --no-run-if-empty dirname)"
      while read package_dir; do
        export npm_package_name="$(echo "$package_dir" | awk -F'/' '{ if ($(NF - 1) ~ /^@/) printf "%s/%s\n", $(NF -1), $NF; else print $NF }')"
        pushd $package_dir
        $SCRIPT
        popd
      done <<< "$package_dirs"
    ''
    ''
      packages_with_gyp="$(find ./node_modules -name "*.gyp" | awk -F'/' '{ if ($3 ~ /^@/) printf "%s/%s\n", $3, $4; else print $3 }' | grep -v "npm" | uniq | tr "\n" " ")"
      npm rebuild $packages_with_gyp
    ''
  ];
}
